package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"warehouse/cache"
	"warehouse/models"
)

type WarehouseController struct {
	beego.Controller
}

func (c *WarehouseController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	var err error

	keyword := c.GetString("people")
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pageSize")

	key := fmt.Sprintf("list_%d_%d", page, pageSize)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	var warehouse models.Warehouse
	var list []models.Warehouse

	if cacheData == "" {
		list, _ := warehouse.List(keyword, page, pageSize)
		if len(list) != 0 {
			jsonData, _ := json.Marshal(list)
			cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour)
		}
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "列表展示失败",
		}
		c.ServeJSON()
		return
	}

	var count int64
	models.DB.Model(&models.Warehouse{}).Count(&count)
	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "列表展示成功",
		"data":    list,
		"count":   count,
	}
	c.ServeJSON()
}
